package com.haven123.cloudapp.rabbitmq.demo;

import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Log4j2
@Component
public class CodeListener {

    public final static String queue_name="test_con2_queue";
    public final static String exchange_name="test_con2_exchange";
    public final static String routingKey_name="test_con2_routing_key";

    @Bean
    public Queue queue(){
        return new Queue(queue_name,false);
    }
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.directExchange(exchange_name).durable(false).build();
    }
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with(routingKey_name).noargs();
    }
    @RabbitListener(queues = queue_name)
    public void listener(Message message, Channel channel,String hello){
        log.info("===========CodeListener==============");
        log.info("message: "+new String(message.getBody(),StandardCharsets.UTF_8));
        log.info(new String(message.getBody(),StandardCharsets.UTF_8));
        log.info("hello : "+hello);
        //do somethong

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("mq ack error",e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                log.error("mq nack error",ex);
            }
        }
    }

}
